<template>
  <div class="form-page">
    <el-form
      ref="dataForm"
      :model="dataForm"
      :rules="dataFormRule"
      :inline="true"
      label-width="10em"
      class="data-form"
    >
      <div class="form-item xy-start al-str">
        <div class="title">基础设置</div>
        <div class="yx-start al-start data">
          <el-form-item
            prop="name"
            label="名称"
          >
            <el-input
              v-model="dataForm.name"
              placeholder="考试名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="开始时间"
            prop="startTime"
          >
            <el-date-picker
              v-model="dataForm.startTime"
              type="datetime"
              placeholder="选择开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%;"
            ></el-date-picker>
          </el-form-item>
          <el-form-item
            label="结束时间"
            prop="endTime"
          >
            <el-date-picker
              v-model="dataForm.endTime"
              type="datetime"
              placeholder="选择结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%;"
            ></el-date-picker>
          </el-form-item>

          <el-form-item
            label="考试时长/分钟"
            prop="answerTime"
          >
            <el-input v-model.number="dataForm.answerTime"></el-input>
          </el-form-item>
          <el-form-item
            label="考试次数"
            prop="answerCount"
          >
            <el-input v-model.number="dataForm.answerCount"></el-input>
          </el-form-item>

          <el-form-item
            label="是否允许迟交"
            prop="delay"
          >
            <el-radio
              v-model="dataForm.delay"
              :label="true"
            >允许</el-radio>
            <el-radio
              v-model="dataForm.delay"
              :label="false"
            >不允许</el-radio>
          </el-form-item>

          <el-form-item
            prop="classificationId"
            label="学科"
          >
            <div class="xy-center">
              <el-cascader
                v-model="dataForm.classificationId"
                v-loading="flag.classfication"
                placeholder="请选择学科"
                :disabled="!from && dataForm.released"
                :options="classificationInfo"
                :show-all-levels="false"
                filterable
                clearable
                :props="{
                                    value: 'id',
                                    label: 'name',
                                    emitPath: false,
                                    checkStrictly: true
                                }"
              ></el-cascader>
            </div>
          </el-form-item>
          <el-form-item
            v-if="from"
            prop="departmentId"
            label="专业"
          >
            <div class="xy-center">
              <el-cascader
                v-model="dataForm.departmentId"
                v-loading="flag.departmentId"
                :disabled="dataForm.released"
                :options="departmentInfo"
                placeholder="请选择专业"
                :show-all-levels="false"
                clearable
                filterable
                :props="{
                                    value: 'id',
                                    label: 'name',
                                    emitPath: false,
                                    checkStrictly: true
                                }"
              >
              </el-cascader>
            </div>
          </el-form-item>
          <el-form-item
            label="课程"
            prop="courseId"
          >
            <div class="table-query-input">
              <el-cascader
                ref="courseRef"
                v-model="dataForm.courseId"
                v-loading="flag.course"
                :options="courseInfo"
                :disabled="dataForm.released"
                placeholder="请选择课程"
                :show-all-levels="false"
                clearable
                filterable
                :props="{
                                    value: 'id',
                                    label: 'courseName',
                                    emitPath: false,
                                    checkStrictly: true
                                }"
              >
              </el-cascader>
            </div>
          </el-form-item>
          <el-form-item
            label="关联章节"
            prop="chapterId"
          >
            <div class="table-query-input">
              <el-cascader
                ref="chapterRef"
                v-model="dataForm.chapterId"
                v-loading="flag.chapter"
                :options="chapterInfo"
                placeholder="请选择章节"
                :show-all-levels="false"
                clearable
                filterable
                :props="{
                                    value: 'id',
                                    label: 'name',
                                    emitPath: false,
                                    checkStrictly: true
                                }"
              >
              </el-cascader>
            </div>
          </el-form-item>
          <el-form-item
            label="下级资源"
            prop="nextResources"
          >
            <div class="table-query-input">
              <el-cascader
                ref="nextResourcesRef"
                v-model="dataForm.nextResources"
                v-loading="flag.nextResources"
                :options="nextResourcesInfo"
                placeholder="请选择"
                :show-all-levels="false"
                clearable
                filterable
                :props="{
                                    value: 'id',
                                    label: 'name',
                                    emitPath: false,
                                    checkStrictly: true
                                }"
              >
              </el-cascader>
            </div>
          </el-form-item>
          <el-form-item
            v-if="dataForm.joinType === 'dep'"
            label="选择班级"
            prop="classIds"
          >
            <div class="table-query-input">
              <el-select
                v-model="dataForm.classIds"
                multiple
                placeholder="请选择班级"
                :disabled="dataForm.released"
              >
                <el-option
                  v-for="item in depInfo"
                  :key="item.id"
                  v-loading="flag.depInfo"
                  :label="item.className"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item
            label="组卷方式"
            prop="ruleType"
          >
            <el-radio
              v-model="dataForm.ruleType"
              :disabled="!dataForm.addAction"
              label="choose"
            >选题组卷</el-radio>
            <el-radio
              v-model="dataForm.ruleType"
              :disabled="!dataForm.addAction"
              label="random"
            >随机组卷</el-radio>
            <el-radio
              v-model="dataForm.ruleType"
              :disabled="!dataForm.addAction"
              label="select"
            >抽题组卷</el-radio>
          </el-form-item>
          <!--                    <el-form-item label="考试说明" prop="remark">-->
          <!--                        <el-input-->
          <!--                            v-model="dataForm.remark"-->
          <!--                            type="textarea"-->
          <!--                            :rows="3"-->
          <!--                        ></el-input>-->
          <!--                    </el-form-item>-->
        </div>
        <el-form-item
          label="考试说明"
          prop="remark"
        >
          <el-input
            v-model="dataForm.remark"
            type="textarea"
            style="width: 1000px"
            :autosize="{ minRows: 8, maxRows: 12 }"
          ></el-input>
        </el-form-item>
      </div>
    </el-form>
    <div
      ref="submitDiv"
      class="form-item xy-center from-operation"
    >
      <el-button
        type="primary"
        icon="el-icon-folder"
        :loading="submitFlag"
        @click="save(false)"
      >保存
      </el-button>
      <el-button
        type="primary"
        icon="el-icon-folder"
        :loading="submitFlag"
        :disabled="dataForm.released"
        @click="save(true)"
      >保存并下一步
      </el-button>
      <el-button
        type="warning"
        icon="el-icon-delete-solid"
        :loading="submitFlag"
        @click="cancle()"
      >取消
      </el-button>
    </div>
  </div>
</template>

<script>
import { FormPage, TablePage } from "@/layout/mixin/iVue.js";
import { mapState } from "vuex";
import { treeList2Tree } from "@/utils/index.js";
import {
  fetchCourseList,
  fetchClassesAll,
  fetchClassificationList2,
  fetchSource,
  fetchChapterList
} from "@/api/course";
import { fetchExamId } from "@/api/exam";
import { fetchDepartmentList } from "@/api/user";
export default {
  name: "AddExamWork",
  components: {},
  mixins: [FormPage, TablePage],
  data () {
    return {
      dataForm: {
        paperType: "chapterText",
        joinType: "dep",
        answerCount: 1
      },
      initForm: {
        paperType: "chapterText",
        joinType: "dep",
        answerCount: 1
      },
      from: false,
      key: 0,
      classificationProps: {
        lazy: true,
        checkStrictly: true,
        emitPath: false,
        lazyLoad: this.getClassification
      },
      flag: {
        classfication: false,
        course: false,
        chapter: false,
        nextResources: false,
        depInfo: false,
        departmentId: false
      },
      courseQueryData: {
        size: 1000,
        courseSubjectId: "",
        schoolMajorId: null
      },
      chapterQueryData: {
        size: 1000,
        baseCourseId: ""
      },
      classficationQueryData: {
        size: 1000
      },
      currentClassificationId: null,
      dataFormRule: {
        name: [
          {
            required: true,
            message: "请输入考试名称",
            trigger: "blur"
          }
        ],

        paperType: [
          {
            required: true,
            message: "请选择考试类型",
            trigger: "change"
          }
        ],
        startTime: [
          {
            required: true,
            message: "请选择开始时间",
            trigger: "change"
          }
        ],
        endTime: [
          {
            required: true,
            message: "请选择结束时间",
            trigger: "change"
          }
        ],
        answerTime: [
          {
            required: true,
            message: "请输入考试耗时",
            trigger: "blur"
          },
          { type: "number", message: "必须为数字值" }
        ],
        answerCount: [
          {
            required: true,
            message: "请输入考试次数",
            trigger: "blur"
          },
          { type: "number", message: "必须为数字值" }
        ],
        ruleType: [
          {
            required: true,
            message: "请选择组卷方式",
            trigger: "change"
          }
        ],
        courseId: [
          { required: true, message: "请选择课程", trigger: "change" }
        ],
        classificationId: [
          { required: true, message: "请选择科目", trigger: "change" }
        ],
        // classIds: [
        //     {required: true, message: "请选择班级", trigger: "change"}
        // ],
        isFinalExam: [
          { required: true, message: "考试类型", trigger: "change" }
        ]
      },
      courseInfo: [],
      chapterInfo: [],
      classificationInfo: [],
      nextResourcesInfo: [],
      depInfo: [],
      departmentInfo: []
    };
  },
  computed: {
    ...mapState({
      status: state => state.status.paperType,
      joinType: state => state.status.joinType,
      ruleType: state => state.status.ruleType
    })
  },
  watch: {
    "dataForm.classificationId" (value) {
      this.handleClassficationId(value);
    },
    "dataForm.departmentId" (value) {
      this.handleDepartmentId(value);
    },
    "dataForm.courseId" (value) {
      this.handleCourseId(value);
    },
    "dataForm.chapterId" (value) {
      this.handleChapterId(value);
    },
    $route: function (to, from) {
      this.initdata();
    }
  },
  mounted () {
    this.initdata();
  },
  methods: {
    initdata () {
      if (this.$route.query.examId) {
        this.dataForm = this.initForm;
        if (this.$route.query.from) {
          this.from = true;
        }
        this.dataForm.addAction = false;
        fetchExamId({ id: this.$route.query.examId }).then(res => {
          this.dataForm = res;
          if (res.classificationId) {
            this.handleClassficationId(
              this.dataForm.classificationId
            );
          }
          if (res.courseId) {
            this.handleCourseId(this.dataForm.courseId);
          }
          if (this.form) {
            this.flag.departmentId = true;
            fetchDepartmentList(
              {
                schoolCode: res.schoolCode,
                type: "xklb",
                size: 1000
              },
              "查询专业信息异常"
            ).then(resp => {
              this.departmentInfo = treeList2Tree(resp);
              this.flag.departmentId = false;
            });
          }
        });
      } else {
        this.dataForm.addAction = true;
      }
    },
    handleChapterId (value) {
      this.nextResourcesInfo = null;
      if (!value) {
        return;
      }
      this.flag.nextResources = true;
      fetchSource({ courseChapterId: value }, "查询章节信息异常").then(
        res => {
          this.nextResourcesInfo = res;
          this.flag.nextResources = false;
        }
      );
    },
    //获取选中学科 查询课程
    handleClassficationId (value) {
      if (this.from) {
        return;
      }
      this.courseInfo = null;
      if (!value) {
        return;
      }
      this.flag.course = true;
      this.courseQueryData.courseSubjectId = value;
      fetchCourseList(this.courseQueryData, "查询课程信息异常").then(
        res => {
          this.courseInfo = treeList2Tree(res);
          this.flag.course = false;
        }
      );
    },
    handleDepartmentId (value) {
      if (!this.from) {
        return;
      }
      this.courseInfo = null;
      if (!value) {
        return;
      }
      this.flag.course = true;
      this.courseQueryData.courseSubjectId = null;
      this.courseQueryData.schoolMajorId = value;
      fetchCourseList(this.courseQueryData, "查询课程信息异常").then(
        res => {
          this.courseInfo = treeList2Tree(res);
          this.flag.course = false;
        }
      );
    },
    handleCourseId (value) {
      this.depInfo = null;
      this.dataForm.classIds = null;
      if (!value) {
        return;
      }
      this.flag.depInfo = true;
      this.flag.chapter = true;
      this.chapterQueryData.baseCourseId = value;
      fetchChapterList(this.chapterQueryData, "查询章节信息异常").then(
        res => {
          this.chapterInfo = treeList2Tree(res);
          this.flag.chapter = false;
        }
      );
      fetchClassesAll({ courseBaseId: value }, "查询班级信息异常").then(
        res => {
          this.depInfo = res;
          this.flag.depInfo = false;
        }
      );
    },
    getClassfication () {
      fetchClassificationList2(this.classficationQueryData).then(res => {
        this.classificationInfo = treeList2Tree(res);
      });
    },
    async loadData () {
      return Promise.all([this.getClassfication()]).catch(e => {
        this.$message.error("数据加载失败，请稍后在试");
      });
    },

    save (flag) {
      this.formDataSave("/exam/exam/update").then(res => {
        if (flag) {
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.replace({
            name: "ExamPaperRe",
            query: {
              examId: res.id,
              ruleType: res.ruleType,
              paperType: res.paperType
            }
          });
        } else {
          this.$store.dispatch("tagsView/delView", this.$route);
          // this.$router.go(-1)
          if (this.from) {
            this.$router.replace({ name: "GroupExamWork" });
          } else {
            this.$router.replace({ name: "SelfExamWork" });
          }
        }
      });
    },
    cancle () {
      this.dataForm = this.initForm;
      this.$store.dispatch("tagsView/delView", this.$route);
      // this.$router.go(-1)
      if (this.from) {
        this.$router.replace({ name: "GroupExamWork" });
      } else {
        this.$router.replace({ name: "SelfExamWork" });
      }
    }
  }
};
</script>

<style lang="css" scoped>
.limit {
  padding: 0 0 0 1.25rem;
  position: relative;
}

.set {
  margin-right: 4.17rem;
  margin-bottom: 1.58rem;
}
.form-page .form-item .data {
  display: grid;
  grid-template-columns: repeat(2, auto);
  grid-column-gap: 50px;
  width: fit-content;
}
</style>
